import { Component } from '@angular/core';
import { forkJoin, Observable } from 'rxjs';

import { FileService } from '@core/base';
import { MinioService, UserMetadata } from '@core/oss/minio';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzUploadFile } from 'ng-zorro-antd/upload';

@Component({
  selector: 'app-minio-action',
  templateUrl: './minio-action.component.html'
})
export class MinioActionComponent {
  fileList: NzUploadFile[] = [];
  userMatadatas: UserMetadata[] = [];

  downloadIds: string = '';
  presignedUrlId?: string;
  deleteId?: string;
  isLoading = false;
  presignedUrl?: string;
  method: string = 'GET';

  constructor(private filesSrc: FileService, private minioSrc: MinioService, private messageSrc: NzMessageService) {}

  beforeUpload = (file: NzUploadFile): boolean => {
    this.fileList = this.fileList.concat(file);
    return false;
  };

  handleUpload(): void {
    const obserList: Array<Observable<any>> = [];
    this.fileList.forEach((file: any) => {
      const formData = new FormData();
      formData.append('file', file);
      obserList.push(this.minioSrc.upload(formData));
    });
    this.isLoading = true;
    forkJoin(obserList).subscribe({
      next: (data: any) => {
        this.isLoading = false;
        this.fileList = [];
        this.userMatadatas = this.userMatadatas.concat(data);
        this.messageSrc.success('upload successfully.');
      },
      error: () => {
        this.isLoading = false;
        this.messageSrc.error('upload failed.');
      }
    });
  }

  download(): void {
    const idList = this.downloadIds.split(',').filter(e => e.trim().length > 0);
    if (idList.length === 0) {
      return;
    }

    this.isLoading = true;
    if (idList.length === 1) {
      this.minioSrc.download(idList[0]).subscribe(data => {
        this.filesSrc.saveAsFile(data, '');
        this.isLoading = false;
      });
    } else {
      this.minioSrc.downloads(idList).subscribe(data => {
        this.filesSrc.saveAsFile(data, '');
        this.isLoading = false;
      });
    }
  }

  delete(): void {
    if (!this.deleteId) {
      return;
    }

    this.isLoading = true;
    this.minioSrc.delete(this.deleteId).subscribe(() => {
      this.messageSrc.success('删除成功');
      this.isLoading = false;
    });
  }

  getPresignedUrl(): void {
    if (!this.presignedUrlId) {
      return;
    }

    this.isLoading = true;
    this.minioSrc.getPresignedObjectUrl(this.presignedUrlId, this.method).subscribe(data => {
      this.presignedUrl = data;
      this.isLoading = false;
    });
  }
}
